<?php
namespace app\modules\api\controllers;

use app\models\Agent;
use app\models\AgentPackage;
use app\models\Card;
use app\models\CardDatalog;
use app\models\WaitActiveCard;
use app\models\UserCardRecharge;
use app\models\CardUsageSub;
use app\models\System;
use app\models\TempCorrect;
use app\models\UserCardReserveRecharge;
use yii\web\Response;
use Yii;
class StatusController extends BasePublicController{

    public function actionTest(){
        //充值时间/第一段开始时间
        $startdate = time();
        $match_time = date('m-d',$startdate);
        $all_end_date = $startdate + (29*86400);
        $all_enddate = strtotime(date("Y-m-d",$all_end_date))+86399;
        
        $card_id = '11';
        $order_sn = date('YmdHis').rand(1000, 9999);
        $data = '0';
        $length_unit = '0';
        //第一段开始时间
        //第一段结束时间
        $first_end = strtotime(date('Y-m-d',$startdate))+86399;
        //第二段开始时间
        $sec_start = $first_end + 1;
        //第二段结束时间
        $sec_end = strtotime('next month',$first_end);
        //第三段开始时间
        $thr_start = $sec_end + 1;
        //第三段结束时间
        
        if($match_time == '02-26'){
            $this->saveCardDatalogs($card_id,$startdate,$first_end,$order_sn,$data,$length_unit);
            $this->saveCardDatalogs($card_id,$sec_start,$sec_end,$order_sn,$data,$length_unit);
            $this->saveCardDatalogs($card_id,$thr_start,$all_enddate,$order_sn,$data,$length_unit);
        }else{
            //第一段结束时间
            $endtimes = strtotime(date('Y-m-d',$startdate))+86399;
            $end_date = $startdate + (29*86400);
            $enddate = strtotime(date("Y-m-d",$end_date))+86399;
            
            //判断订购日期是否大于或小于等于本周期最后一天
            if($startdate > $endtimes ){
                //如果订购日期大于本周期最后一天，获取下个周期第一天的日期
                $endtime = strtotime(date('Y-m-d',strtotime(date('Y-m-27',strtotime("+1 month -1 day")))));
            }elseif($startdate <= $endtimes){
                //订购日期小于等于本周期最后一天，获取本月下一周期第一天
                $endtime = strtotime(date('Y-m-d',strtotime(date('Y-m-27'))));
                $endtimet = strtotime(date('Y-m-d',strtotime(date('Y-m-26'))))+86399;
            }
            //判断上一步判断得到的时间是否大于或小于等于到期时间，执行不同的操作
            if($endtime > $end_date){
                $this->saveCardDatalogs($card_id,$startdate,$enddate,$order_sn,$data,$length_unit);
            }elseif($endtime <= $end_date){
                if($startdate > $endtimes){
                    // $endtimet = strtotime(date('Y-m-d',strtotime(date('Y-m-26',strtotime('next month')))))+86399;
                    // $endtime = strtotime(date('Y-m-d',strtotime(date('Y-m-27',strtotime('next month')))));
                    $endtimet = strtotime(date('Y-m-26',strtotime("+ 1 month -1 day")))+86399;
                    $endtime = strtotime(date('Y-m-27',strtotime("+ 1 month -1 day")));
                    
                }
                $this->saveCardDatalogs($card_id,$startdate,$endtimet,$order_sn,$data,$length_unit);
                $this->saveCardDatalogs($card_id,$endtime,$enddate,$order_sn,$data,$length_unit);
            }
        }
        
    }
    private function saveCardDatalogs($card_id,$startdate,$enddate,$order_sn,$data,$length_unit){
        $dataLog = new CardDatalog();
        $dataLog->card_id = $card_id;
        $dataLog->startdate = $startdate;
        $dataLog->enddate = $enddate;
        $dataLog->order_sn = $order_sn;
        $dataLog->data = 0;
        $dataLog->length_unit = $length_unit;
        $dataLog->save();
    }

    public function saveDatalog(){
    	//获取本月27号
    	$str = date('Y-m-27');
        //获取本周期最后一天
        $endtimes = strtotime(date('Y-m-d',strtotime(date('Y-m-26'))))+86399;
        $enddate = strtotime(date("Y-m-d",$this->enddate))+86399;
        //判断订购日期是否大于或小于等于本周期最后一天
        if($this->startdate > $endtimes ){
            //如果订购日期大于本周期最后一天，获取下个周期第一天的日期
            // $endtime = strtotime(date('Y-m-d',strtotime(date('Y-m-27',strtotime("+1 month -1 day")))));
            $endtime = strtotime('next month',strtotime($str));
        }elseif($this->startdate <= $endtimes){
            //订购日期小于等于本周期最后一天，获取本月下一周期第一天
            $endtime = strtotime(date('Y-m-d',strtotime(date('Y-m-27'))));
            $endtimet = strtotime(date('Y-m-d',strtotime(date('Y-m-26'))))+86399;
        }
        //判断上一步判断得到的时间是否大于或小于等于到期时间，执行不同的操作
        if($endtime > $this->enddate){
            $this->saveCardDataLog($this->card_id,$this->startdate,$enddate,$this->order_sn,$this->data);
        }elseif($endtime <= $this->enddate){
            if($this->startdate > $endtimes){
                // $endtimet = strtotime(date('Y-m-26',strtotime("+ 1 month -1 day")))+86399;
                // $endtime = strtotime(date('Y-m-27',strtotime("+ 1 month -1 day")));
                $endtimet = strtotime('next month',strtotime($str)) - 1 ;
                $endtime = strtotime('next month',strtotime($str));
                
            }
            $this->saveCardDatalog($this->card_id,$this->startdate,$endtimet,$this->order_sn,$this->data);
            $this->saveCardDatalog($this->card_id,$endtime,$enddate,$this->order_sn,$this->data);
        }
    }

    public function actionAgent(){
        $redis = Yii::$app->redis;
        $len = $redis->llen('agent');
        if($len == 0){
            Yii::$app->db->createCommand()->update('agent', ['average_create_status' => 0])->execute(); 
        }
		$agent = Agent::find()->where(['average_create_status'=>0])->all();
		foreach ($agent as $key => $value) {
			$agent_id = $value['id'];
			$agent_name = $value['username'];
		}
		if(empty($agent)){
            return ['code'=>0,'msg'=>'没有代理商了'];
		}else{
			//把循环出来的代理商全部写入list
			$agent_list = $redis->lpush('agent',$agent_name);
			Yii::$app->db->createCommand()->update('agent', ['average_create_status' => 1], 'id = :id',['id' => $agent_id])->execute(); 
            return ['code'=>1,'agent'=>$agent_name,'msg'=>'代理商写入成功'];
		}	
	}
    //写入数据的平均用量
    public function actionAverage(){
        $analyse = new UserCardRecharge();
		$count = array();
		$average = array();
		$redis = Yii::$app->redis;
		for ($i=1; $i <13 ; $i++) { 
			$months = date('Y-m',strtotime("-$i month"));
            $days = date('t',strtotime($months));
			$start_time = strtotime($months);
			$end_time = $start_time + ($days*86400)-1;
			$agent_list = $redis->lrange('agent',0,0);
			$agent = Agent::findOne(['username'=>$agent_list]);
			$counts = UserCardRecharge::find()->andFilterWhere(['agent_id'=>$agent->id])->andFilterWhere(['between','create_time',$start_time,$end_time])->andFilterWhere(['<','recharge_type','3'])->count();
			$card_count = $counts / 1000;
			array_push($count,$card_count);
			if(!empty($agent->id)){
				$arr = Yii::$app->db->createCommand("SELECT `card`.`id` FROM card WHERE `card`.`agent_id` = ".$agent->id."")->queryAll(); 
			}else{
				$arr = Yii::$app->db->createCommand("SELECT `card`.`id` FROM card where `status` > '3'")->queryAll(); 
				$name = 'all';
			}
            $xuzhi = '0.6';
            $card_id = array_column($arr,'id');
            $im = implode(',',$card_id);
			$ids = explode(',', $im);
			$sumdata = CardDatalog::find()->andFilterWhere(['between','startdate',$start_time,$end_time])->andWhere(['in', 'card_id', $ids])->sum('data');
            $total = $sumdata * $xuzhi;
			if($card_count == 0){
				$average_data = 0;
			}else{
				$result = $total / $counts;
				$average_data = $analyse->formatUsage($result);
			}
			array_push($average,$average_data);	
		}
		$val = array_merge($count,$average);
		if(!empty($agent_list)){
			$redis->hset('average_data',$agent->username,json_encode($val));
            $redis->lrem('agent',0,$agent->username);
			return ['code'=>1,'agent'=>$agent->username,'msg'=>'数据添加完成'];
		}else{
            $redis->hset('average_data',$name,json_encode($val));
            return ['code'=>0,'msg'=>'数据全部执行完毕'];
        }
    }
    /**
     * 激活卡
     */
	public function actionSetStatus(){
        //读取待激活数据
        $card = WaitActiveCard::find()->andFilterWhere(['<','fail_number',3])->andFilterWhere(['is_refresh'=>0])->orderBy('id desc')->one();
        $iccid = Card::find()->where(['iccid'=>$card->iccid])->one();
        if(empty($card)){
            return ['code' => 0,'msg' => '暂时没有卡等待激活'];
            exit;
        }
        $data = array(
            'appkey' => 'SD#xlwl$201807',
            'token'  => '3cf8d9917d4e483a57d3a7e88841c7737414339aa3e93ac9f4a6878bb21324a3',
            'apicode' => 'setCardStatus',
            'iccid'  => $card->iccid,
            'setStatus' => "4",
            'source' => "chongzhijihuo"
        );
        $string = json_encode($data);
        $config = System::findOne(['name'=>'api_url']);
        $url = $config->value;
        $cuiotPost =  $this->postUrl($url,$string);
        $arr = json_decode($cuiotPost,true);
        if($arr['retcode'] == 200){
            if($card->length_unit == 99){
                $iccid->newRefreshBasic();
                $result = WaitActiveCard::deleteAll(['id'=>$card->id]);
            }else{
                Yii::$app->db->createCommand()->update('wait_active_card', ['is_refresh' => 1], 'id = :id',['id' => $card->id])->execute();
            }
            \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            return ['code' => 1,'iccid' => $card->iccid,'msg' => '激活成功'];
        }else{
            //如果失败，就把错误次数加一
            $fail = $card->fail_number + 1;
            Yii::$app->db->createCommand()->update('wait_active_card', ['fail_number' => $fail], 'id = :id',['id' => $card->id])->execute(); 
            \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            return ['code' => 0,'iccid' => $card->iccid,'msg' => '失败'];
        }
    }
    
    public function actionSetStatusSecond(){
        //读取待激活数据
        $card = WaitActiveCard::find()->andFilterWhere(['<','fail_number',3])->andFilterWhere(['is_refresh'=>0])->one();
        $iccid = Card::find()->where(['iccid'=>$card->iccid])->one();
        if(empty($card)){
            return ['code' => 0,'msg' => '暂时没有卡等待激活'];
            exit;
        }
        $data = array(
            'appkey' => 'SD#xlwl$201807',
            'token'  => '3cf8d9917d4e483a57d3a7e88841c7737414339aa3e93ac9f4a6878bb21324a3',
            'apicode' => 'setCardStatus',
            'iccid'  => $card->iccid,
            'setStatus' => "4",
            'source' => "chongzhijihuo"
        );
        $string = json_encode($data);
        $config = System::findOne(['name'=>'api_url']);
        $url = $config->value;
        $cuiotPost =  $this->postUrl($url,$string);
        $arr = json_decode($cuiotPost,true);
        if($arr['retcode'] == 200){
            if($card->length_unit == 99){
                $iccid->newRefreshBasic();
                $result = WaitActiveCard::deleteAll(['id'=>$card->id]);
            }else{
                Yii::$app->db->createCommand()->update('wait_active_card', ['is_refresh' => 1], 'id = :id',['id' => $card->id])->execute();
            }
            \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            return ['code' => 1,'iccid' => $card->iccid,'msg' => '激活成功'];
        }else{
            //如果失败，就把错误次数加一
            $fail = $card->fail_number + 1;
            Yii::$app->db->createCommand()->update('wait_active_card', ['fail_number' => $fail], 'id = :id',['id' => $card->id])->execute(); 
            \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            return ['code' => 0,'iccid' => $card->iccid,'msg' => '失败'];
        }
    }
    /**
     * 把激活失败的卡重新加入激活队列
     */
    public function actionAgainExecute(){
        //读取待激活数据
        $card = WaitActiveCard::find()->andFilterWhere(['fail_number'=>3])->orderBy('id desc')->one();
        if(empty($card)){
            return ['code'=>0,'msg'=>'暂时没有卡要重新加入激活队列'];
            exit;
        }
        Yii::$app->db->createCommand()->update('wait_active_card', ['fail_number' => 0], 'id = :id',['id' => $card->id])->execute(); 
        return ['code'=>1,'iccid'=>$card->iccid,'msg'=>'加入激活队列成功'];
    }
    /**
     * 执行流量修正
     */
    public function actionCorrectFlow(){
        //获取要执行的卡
        $wait_card = WaitActiveCard::find()->andFilterWhere(['is_refresh'=>1])->orderBy('id desc')->one();
        if(empty($wait_card)){
            return ['code'=>0,'msg'=>'没有需要执行流量修正的卡'];
            exit;
        }else{
            $card = Card::find()->andFilterWhere(['iccid'=>$wait_card->iccid])->one();
            $card->newRefreshBasic();
            //获取上个周期的编号
            $ordersn = (new \yii\db\Query())
            ->select(['order_sn'])
            ->from('card_datalog')
            ->where(['card_id'=>$card->id])
            ->offset(1)
            ->groupBy('order_sn')
            ->orderBy('card_datalog.id desc')
            ->all();
            //获取上个周期第二阶段的用量信息
            $last = CardDataLog::find()->where(['order_sn'=>$ordersn[0]['order_sn']])->orderBy('id desc')->one();
            if(empty($last)){
                $result = WaitActiveCard::deleteAll(['id'=>$wait_card->id]);
                return ['code'=>0,'iccid'=>$wait_card->iccid,'msg'=>'尚未产生流量，无需修正!'];
                exit;
            }
                //获取当前周期用量
                $current = CardDataLog::find()->where(['order_sn'=>$card->order_sn])->one();
                if($card->is_correct == 0){
                    if($card->data > 0){
                        //把上个周期第二阶段的用量和本周期第一阶段的用量相加
                        $usage = $last->data + $current->data;
                        //把相加得到的用量保存到上周期第二阶段
                        $corrected = CardDatalog::findOne(['id'=>$last->id]);
                        $corrected->data = $usage;
                        $corrected->save();
                    Yii::$app->db->createCommand()->update('card', ['is_correct' => 1], 'id = :id',['id' => $card->id])->execute(); 
                    $card->newRefreshBasic();
                    $result = WaitActiveCard::deleteAll(['id'=>$wait_card->id]);
                    return ['code'=>1,'iccid'=>$wait_card->iccid,'msg'=>'流量修正完成!'];
                }else{
                    //得到正确的用量
                    $real_usage = $last->data + $current->data;
                    //把本周期第一阶段的用量保存到上周期第二阶段
                    $corrected = CardDatalog::findOne(['id'=>$last->id]);
                    $corrected->data = $real_usage;
                    $corrected->save();
                    Yii::$app->db->createCommand()->update('card', ['is_correct' => 1], 'id = :id',['id' => $card->id])->execute(); 
                    $card->newRefreshBasic();
                    $result = WaitActiveCard::deleteAll(['id'=>$wait_card->id]);
                    return ['code'=>1,'iccid'=>$wait_card->iccid,'msg'=>'流量修正完成!'];
                }
            }else{
                $result = WaitActiveCard::deleteAll(['id'=>$wait_card->id]);
                return ['code'=>0,'iccid'=>$wait_card->iccid,'msg'=>'卡已经修正流量，无需再次修正!'];
            }
        }
    }
    /**
     * 生成卡周期流量统计
     */
    public function actionGenerateUsage(){
        $card = Card::find()->where(['>','dgcs','1'])->andWhere(['is_sub'=>0])->one();
        if(empty($card)){
            \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            return ['code'=>0,'msg'=>'没有符合条件的卡'];
            Yii::$app->db->createCommand()->update('card', ['is_sub' => 0])->execute(); 
            exit;
        }
        $sub = CardUsageSub::find()->where(['card_id'=> $card->id])->all();
        $time = (29*86400);
        //先删除表中已经存在的记录
        $usage = CardUsageSub::deleteAll(['card_id'=>$card->id]);
        //循环查询出card_datalog表中的记录
        for ($i=1; $i <3 ; $i++) { 
            $profitList = (new \yii\db\Query())
            ->select(['card_datalog.id','card_datalog.card_id','card_datalog.order_sn','card_datalog.startdate','sum(card_datalog.data) as sum_data'])
            ->from('card_datalog')
            ->groupBy('card_datalog.order_sn')
            ->andFilterWhere(['card_datalog.card_id'=>$card->id])
            ->offset($i)
            ->limit(1)
            ->orderBy('id desc')
            ->all();
            //再取出需要的记录
            $recharge = UserCardRecharge::findOne(['create_time'=>$profitList[0]['startdate']]);
            //因为卡被清除，充值记录删除，判断充值记录是否为空
            if(empty($recharge)){
                Yii::$app->db->createCommand()->update('card', ['is_sub' => 1], 'id = :id',['id' => $card->id])->execute(); 
            }
            //查询套餐虚值
            $xuzhi = AgentPackage::findOne(['agent_id'=>$card->agent_id,'package_id'=>$recharge->package_id]);
            //判断虚值是否为空，然后赋值
            if(empty($xuzhi)){
                $fakeNumber = 0.75;
            }else{
                $fakeNumber = $xuzhi->xuzhi;
            }
            //计算用量并写入表中
            foreach ($profitList as $key => $value) {
                $sub = new CardUsageSub();
                $sub->agent_id = $card->agent_id;
                $sub->card_id = $value['card_id'];
                $sub->package_id = $recharge->package_id;
                $sub->start_date = $value['startdate'];
                $end_date = $value['startdate'] + $time;
                $sub->end_date = strtotime(date('Y-m-d',$end_date))+86399;
                $sub->data_isp = $value['sum_data'];
                $sub->data = $value['sum_data'] /$fakeNumber ;
                $sub->create_time = time();
                $sub->save(); 
                Yii::$app->db->createCommand()->update('card', ['is_sub' => 1], 'id = :id',['id' => $card->id])->execute(); 
            }    
        }
        //返回结果
        \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        return ['code'=>'1','iccid'=>$card->iccid,'msg'=>'统计记录生成成功'];
    }

    //临时流量修正
    public function actionCorrectFlowTemp(){
        //获取要执行的卡
        $wait_card = WaitActiveCard::find()->andFilterWhere(['is_refresh'=>1])->one();
        
        if(empty($wait_card)){
            return ['code'=>0,'msg'=>'没有需要执行流量修正的卡'];
            exit;
        }else{
            $card = Card::find()->andFilterWhere(['iccid'=>$wait_card->iccid])->one();
            $card->newRefreshBasic();
            //获取上个周期的编号
            $ordersn = (new \yii\db\Query())
            ->select(['order_sn'])
            ->from('card_datalog')
            ->where(['card_id'=>$card->id])
            ->offset(1)
            ->groupBy('order_sn')
            ->orderBy('card_datalog.id desc')
            ->all();
            //获取上个周期第二阶段的用量信息
            $last = CardDataLog::find()->where(['order_sn'=>$ordersn[0]['order_sn']])->orderBy('id desc')->one();
            if(empty($last)){
                $result = WaitActiveCard::deleteAll(['id'=>$wait_card->id]);
                return ['code'=>0,'iccid'=>$wait_card->iccid,'msg'=>'尚未产生流量，无需修正!'];
                exit;
            }
                //获取当前周期用量
                $current = CardDataLog::find()->where(['order_sn'=>$card->order_sn])->one();
                if($card->is_correct == 0){
                    if($card->data > 0){
                        //把上个周期第二阶段的用量和本周期第一阶段的用量相加
                        $usage = $last->data + $current->data;
                        //把相加得到的用量保存到上周期第二阶段
                        $corrected = CardDatalog::findOne(['id'=>$last->id]);
                        $corrected->data = $usage;
                        $corrected->save();
                    Yii::$app->db->createCommand()->update('card', ['is_correct' => 1], 'id = :id',['id' => $card->id])->execute(); 
                    $card->newRefreshBasic();
                    $result = WaitActiveCard::deleteAll(['id'=>$wait_card->id]);
                    return ['code'=>1,'iccid'=>$wait_card->iccid,'msg'=>'流量修正完成!'];
                }else{
                    //得到正确的用量
                    $real_usage = $last->data + $current->data;
                    //把本周期第一阶段的用量保存到上周期第二阶段
                    $corrected = CardDatalog::findOne(['id'=>$last->id]);
                    $corrected->data = $real_usage;
                    $corrected->save();
                    Yii::$app->db->createCommand()->update('card', ['is_correct' => 1], 'id = :id',['id' => $card->id])->execute(); 
                    $card->newRefreshBasic();
                    $result = WaitActiveCard::deleteAll(['id'=>$wait_card->id]);
                    return ['code'=>1,'iccid'=>$wait_card->iccid,'msg'=>'流量修正完成!'];
                }
            }else{
                $result = WaitActiveCard::deleteAll(['id'=>$wait_card->id]);
                return ['code'=>0,'iccid'=>$wait_card->iccid,'msg'=>'卡已经修正流量，无需再次修正!'];
            }
        }
    }

    /**
     * 临时刷新卡
     */
    public function actionTempRefresh(){
        $card = TempCorrect::find()->orderBy('id desc')->one();
        if(empty($card)){
            return ['code'=>'0','msg'=>'没有需要执行的卡'];
        }
        $abc = Card::findOne(['iccid'=>$card->iccid]);
        $endate = $abc->active_time + (29*86400);
        $endtime = strtotime(date('Y-m-d',$endate))+86399;
        $data = array(
            'appkey' => 'SD#xlwl$201807',
            'token'  => '3cf8d9917d4e483a57d3a7e88841c7737414339aa3e93ac9f4a6878bb21324a3',
            'apicode' => 'CardCycle',
            'iccid'  => $card->iccid
            );
        $string = json_encode($data);
        $config = System::findOne(['name'=>'api_url']);
        $url = $config->value;
        $cuiotPost =  $this->postUrl($url,$string);
        $arr = json_decode($cuiotPost,true);
        if($arr['retcode'] == '200'){
            $result = TempCorrect::deleteAll(['id'=>$card->id]);
            Yii::$app->db->createCommand()->update('card', ['term_end_time' => $endtime], 'id = :id',['id' => $abc->id])->execute();
            return ['code'=>'1','iccid'=>$card->iccid,'msg'=>'刷新成功'];
            
        }else{
            return ['code'=>'0','iccid'=>$card->iccid,'msg'=>'刷新失败'];
        }
    }
    /**
     * 临时
     */
    public function actionTempPoint(){
        $trade = TempCorrect::findOne(['status'=>0]);
        if(empty($trade)){
            return ['code'=>'0','msg'=>'没有记录'];
        }
        $recharge = UserCardRecharge::findOne(['trade_no'=>$trade->trade]);
        if(empty($recharge)){
            Yii::$app->db->createCommand()->update('temp_correct', ['status' => 1], 'id = :id',['id' => $trade->id])->execute();
            return ['code'=>'0','msg'=>'没有找到对应的充值记录'];
        }else{
            $result = TempCorrect::deleteAll(['id'=>$trade->id]);
            return ['code'=>'0','msg'=>'已经找到对应记录'];
        }
    }

    public function actionRandom(){
        $start = '1596211200';
        $end = '1598803199';
        $point = rand($start,$end);
        $temp = TempCorrect::findOne(['create_time'=>0]);
        if(empty($temp)){
            
            return ['code'=>'0','msg'=>'没有记录了'];
        }else{
            Yii::$app->db->createCommand()->update('temp_correct', ['create_time' => $point], 'id = :id',['id' => $temp->id])->execute();
            return ['code'=>'1','msg'=>'写入成功'];
        }

    }
    

    public function actionIp(){
        $ip = $_SERVER['REMOTE_ADDR'];
        $token = '4b8b146c95e12b448a4162b9d4175f63';
        $result = $this->curl_get($ip,$token); 
        echo $result;
    }
	public function postUrl($url,$data_string){
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json',
            'Content-Length: ' . strlen($data_string)));
        $result = curl_exec($ch);
        if (curl_errno($ch)) {
            print curl_error($ch);
        }
        curl_close($ch);
        return $result;
    }

    //检测校正卡激活时间
    public function actionCorrectReserve(){
        if(empty($this->get('time'))){
            $time = strtotime(date('Y-m-d'));
        }else{
            $time = strtotime($this->get('time'));
        }
        $reserve = UserCardReserveRecharge::find()->andFilterWhere(['active_time'=>$time])->andFilterWhere(['execute_status'=>'2'])->andFilterWhere(['jz_status'=>'0'])->one();
        $count = UserCardReserveRecharge::find()->andFilterWhere(['active_time'=>$time])->andFilterWhere(['execute_status'=>'2'])->andFilterWhere(['jz_status'=>'0'])->count();
        if(empty($reserve)){
            return ['code'=>0,'msg'=>'没有要执行的了'];
        }
        $before_active = date('Y-m-d',$reserve->active_time);
        $card = Card::findOne(['id'=>$reserve->card_id]);
        $reserve->active_time = $card->term_end_time + 1;
        $reserve->jz_status = '1';
        $reserve->save();
        $after_active = date('Y-m-d',$card->term_end_time + 1);
        if($before_active != $after_active){
            Yii::$app->db->createCommand()->update('user_card_reserve_recharge', ['jz_status' => 2], 'id = :id',['id' => $reserve->id])->execute();
        }
        return ['code'=>1,'iccid'=>$card->iccid,'msg'=>'原激活时间：'.$before_active.'修正为：'.$after_active,'count'=>'剩余数量：'.$count];
    }
    /**
     * 对应日期添加一条datalog记录
     */
    public function actionAddDataLog(){
        $date = $this->get('date');
        $start = strtotime($date);
        $end = strtotime($date) + 86399;
        $dataLog = CardDatalog::find()->andFilterWhere(['between','startdate',$start,$end])->andFilterWhere(['extra_signal'=>0])->one();
        $card = Card::findOne(['id'=>$dataLog->card_id]);
        if(!empty($dataLog)){
            $log = new CardDatalog();
            $log->card_id = $dataLog->card_id;
            $log->startdate = $dataLog->enddate + 1;
            $log->enddate = $dataLog->enddate + 86400;
            $log->order_sn = $dataLog->order_sn;
            $log->save();
            Yii::$app->db->createCommand()->update('card_datalog', ['extra_signal' => 1], 'order_sn = :order_sn',['order_sn' => $dataLog->order_sn])->execute();
            return ['code'=>200,'iccid'=>$card->iccid,'message'=>'操作成功'];
        }else{
            return ['code'=>404,'message'=>'没有找到符合条件的数据'];
        }
    }

    public function curl_get($ip, $token)
    {
        // 初始化
        $ch = curl_init();
        // 设置变量
        curl_setopt($ch, CURLOPT_URL, sprintf('https://67ip.cn/check?ip=%s&token=%s', $ip, $token));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
        // 执行并获取结果
        $output = curl_exec($ch);
        // 释放cURL句柄
        curl_close($ch);
        return $output;
    }

}